package com.itboy.mall.pms.skuinfo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.itboy.common.utils.PageUtils;
import com.itboy.common.core.page.PagePlus;
import com.itboy.common.core.page.TableDataInfo;
import com.itboy.framework.config.ThreadPoolConfig;
import com.itboy.mall.pms.attrattrgroup.service.IMallAttrAttrGroupService;
import com.itboy.mall.pms.attrgroup.service.IMallAttrGroupService;
import com.itboy.mall.pms.brand.domain.MallBrand;
import com.itboy.mall.pms.brand.service.IMallBrandService;
import com.itboy.mall.pms.category.domain.MallCategory;
import com.itboy.mall.pms.category.service.IMallCategoryService;
import com.itboy.mall.pms.product.vo.SkuItemSaleAttrVo;
import com.itboy.mall.pms.product.vo.SkuItemVo;
import com.itboy.mall.pms.product.vo.SpuItemAttrGroupVo;
import com.itboy.mall.pms.spuinfodesc.domain.MallSpuInfoDesc;
import com.itboy.mall.pms.spuinfodesc.service.IMallSpuInfoDescService;
import com.itboy.mall.sms.memberprice.domain.MallMemberPrice;
import com.itboy.mall.sms.memberprice.service.IMallMemberPriceService;
import com.itboy.mall.sms.skufullreduction.domain.MallSkuFullReduction;
import com.itboy.mall.sms.skufullreduction.service.IMallSkuFullReductionService;
import com.itboy.mall.pms.skuimages.domain.MallSkuImages;
import com.itboy.mall.pms.skuimages.service.IMallSkuImagesService;
import com.itboy.mall.sms.skuladder.domain.MallSkuLadder;
import com.itboy.mall.sms.skuladder.service.IMallSkuLadderService;
import com.itboy.mall.pms.skusaleattrvalue.domain.MallSkuSaleAttrValue;
import com.itboy.mall.pms.skusaleattrvalue.service.IMallSkuSaleAttrValueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.itboy.common.core.mybatisplus.core.ServicePlusImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itboy.mall.pms.skuinfo.bo.MallSkuInfoAddBo;
import com.itboy.mall.pms.skuinfo.bo.MallSkuInfoQueryBo;
import com.itboy.mall.pms.skuinfo.bo.MallSkuInfoEditBo;
import com.itboy.mall.pms.skuinfo.domain.MallSkuInfo;
import com.itboy.mall.pms.skuinfo.mapper.MallSkuInfoMapper;
import com.itboy.mall.pms.skuinfo.vo.MallSkuInfoVo;
import com.itboy.mall.pms.skuinfo.service.IMallSkuInfoService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

/**
 * sku信息Service业务层处理
 *
 * @author itboy
 * @date 2021-08-08
 */
@Service
public class MallSkuInfoServiceImpl extends ServicePlusImpl<MallSkuInfoMapper, MallSkuInfo> implements IMallSkuInfoService {

	@Autowired
	private IMallBrandService iMallBrandService;

	@Autowired
	private IMallCategoryService iMallCategoryService;

	@Autowired
	private IMallSkuInfoService iMallSkuInfoService;

	@Autowired
	private ThreadPoolConfig threadPoolConfig;

	/**
	 * sku 保存销售属性 service
	 */
	@Autowired
	private IMallSkuSaleAttrValueService iMallSkuSaleAttrValueService;

	/**
	 * sku 保存图集 service
	 */
	@Autowired
	private IMallSkuImagesService iMallSkuImagesService;

	/**
	 * sku 商品满减信息 service
	 */
	@Autowired
	private IMallSkuFullReductionService iMallSkuFullReductionService;


	/**
	 * sku 商品阶梯价格  满几件打几折 service
	 */
	@Autowired
	private IMallSkuLadderService iMallSkuLadderService;

	/**
	 * sku 商品会员价格 service
	 */
	@Autowired
	private IMallMemberPriceService iMallMemberPriceService;

	@Autowired
	private IMallSpuInfoDescService iMallSpuInfoDescService;

	@Autowired
	private IMallAttrGroupService iMallAttrGroupService;

    @Override
    public MallSkuInfoVo queryById(Long skuId){
        return getVoById(skuId, MallSkuInfoVo.class);
    }

    @Override
    public TableDataInfo<MallSkuInfoVo> queryPageList(MallSkuInfoQueryBo bo) {
        PagePlus<MallSkuInfo, MallSkuInfoVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo), MallSkuInfoVo.class);
		List<MallSkuInfoVo> recordsVo = result.getRecordsVo();
		if(CollectionUtil.isNotEmpty(recordsVo)){
			//分类
			List<Long> catalogIdList = recordsVo.stream().map(e -> e.getCatalogId()).collect(Collectors.toList());
			LambdaQueryWrapper<MallCategory> catalogWrapper = new LambdaQueryWrapper<>();
			catalogWrapper.in(MallCategory::getId,catalogIdList);
			List<MallCategory> mallCategoryList = iMallCategoryService.list(catalogWrapper);
			recordsVo.forEach(e->{
				MallCategory mallCategory = mallCategoryList.stream().filter(t -> t.getId().equals(e.getCatalogId())).findFirst().orElse(null);
				if(ObjectUtil.isNotNull(mallCategory)){
					e.setCatalogName(mallCategory.getName());
				}
			});

			//品牌
			List<Long> brandIdList = recordsVo.stream().map(e -> e.getBrandId()).collect(Collectors.toList());
			LambdaQueryWrapper<MallBrand> brandWrapper = new LambdaQueryWrapper<>();
			brandWrapper.in(MallBrand::getBrandId,brandIdList);
			List<MallBrand> mallBrandList = iMallBrandService.list(brandWrapper);

			recordsVo.forEach(e->{
				MallBrand mallBrand = mallBrandList.stream().filter(t -> t.getBrandId().equals(e.getBrandId())).findFirst().orElse(null);
				if(ObjectUtil.isNotNull(mallBrand)){
					e.setBrandName(mallBrand.getName());
				}
			});
		}
		result.setRecordsVo(recordsVo);
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<MallSkuInfoVo> queryList(MallSkuInfoQueryBo bo) {
        return listVo(buildQueryWrapper(bo), MallSkuInfoVo.class);
    }

    private LambdaQueryWrapper<MallSkuInfo> buildQueryWrapper(MallSkuInfoQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<MallSkuInfo> lqw = Wrappers.lambdaQuery();
		lqw.eq(bo.getSpuId()!= null, MallSkuInfo::getSpuId, bo.getSpuId());
        lqw.like(StrUtil.isNotBlank(bo.getSkuName()), MallSkuInfo::getSkuName, bo.getSkuName());
        lqw.eq(StrUtil.isNotBlank(bo.getSkuDesc()), MallSkuInfo::getSkuDesc, bo.getSkuDesc());
        lqw.eq(bo.getCatalogId() != null, MallSkuInfo::getCatalogId, bo.getCatalogId());
        lqw.eq(bo.getBrandId() != null, MallSkuInfo::getBrandId, bo.getBrandId());
        lqw.eq(StrUtil.isNotBlank(bo.getSkuTitle()), MallSkuInfo::getSkuTitle, bo.getSkuTitle());
        lqw.eq(StrUtil.isNotBlank(bo.getSkuSubtitle()), MallSkuInfo::getSkuSubtitle, bo.getSkuSubtitle());
		if(bo.getBeginPrice()!=null){
			lqw.ge(MallSkuInfo::getPrice,bo.getBeginPrice());
		}
		if(bo.getEndPrice()!=null){
			lqw.le(MallSkuInfo::getPrice,bo.getEndPrice());
		}
        return lqw;
    }

    @Override
    public Boolean insertByAddBo(MallSkuInfoAddBo bo) {
        MallSkuInfo add = BeanUtil.toBean(bo, MallSkuInfo.class);
        validEntityBeforeSave(add);
        return save(add);
    }

    @Override
    public Boolean updateByEditBo(MallSkuInfoEditBo bo) {
        MallSkuInfo update = BeanUtil.toBean(bo, MallSkuInfo.class);
        validEntityBeforeSave(update);
        return updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(MallSkuInfo entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
	@Transactional
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
		//刪除 mall_sku_images
		iMallSkuImagesService.remove(new LambdaQueryWrapper<MallSkuImages>().in(MallSkuImages::getSkuId,ids));
		//刪除 mall_sku_sale_attr_value 銷售属性
		iMallSkuSaleAttrValueService.remove(new LambdaQueryWrapper<MallSkuSaleAttrValue>().in(MallSkuSaleAttrValue::getSkuId,ids));
		//刪除 mall_sku_ladder 满减信息 满几件打几折
		iMallSkuLadderService.remove(new LambdaQueryWrapper<MallSkuLadder>().in(MallSkuLadder::getSkuId,ids));
		//删除 mall_member_price 会员价格
		iMallMemberPriceService.remove(new LambdaQueryWrapper<MallMemberPrice>().in(MallMemberPrice::getSkuId,ids));
		//删除 mall_sku_full_reduction 满减信息
		iMallSkuFullReductionService.remove(new LambdaQueryWrapper<MallSkuFullReduction>().in(MallSkuFullReduction::getSkuId,ids));
		//刪除 skuInfo  mall_sku_info
		return removeByIds(ids);
    }

	@Override
	public MallSkuInfoVo queryInfoById(Long skuId) {
		MallSkuInfoVo mallSkuInfoVo = iMallSkuInfoService.queryById(skuId);
		String[] recursionById = iMallCategoryService.getRecursionById(mallSkuInfoVo.getCatalogId());
		mallSkuInfoVo.setCatalogIds(recursionById);
		return mallSkuInfoVo;
	}

	@Override
	public SkuItemVo itemBySkuId(Long skuId) throws ExecutionException, InterruptedException {
		SkuItemVo skuItemVo = new SkuItemVo();
    	//1.sku基本信息
		CompletableFuture<MallSkuInfo> future = CompletableFuture.supplyAsync(() -> {
			MallSkuInfo skuInfo = iMallSkuInfoService.getById(skuId);
			skuItemVo.setMallSkuInfo(skuInfo);
			return skuInfo;
		}, threadPoolConfig.threadPoolTaskExecutor());


		//2.获取spu的销售属性组合
		CompletableFuture<Void> saleAttrFuture  = future.thenAcceptAsync((res) -> {
			List<SkuItemSaleAttrVo> skuItemSaleAttrVoList = iMallSkuSaleAttrValueService.getSaleAttrBySpuId(res.getSpuId());
			skuItemVo.setSaleAttr(skuItemSaleAttrVoList);
		},threadPoolConfig.threadPoolTaskExecutor());

		//3、获取spu的规格参数信息
		CompletableFuture<Void> baseAttrFuture = future.thenAcceptAsync((res) -> {
			List<SpuItemAttrGroupVo> attrGroupVos = iMallAttrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
			skuItemVo.setGroupAttrs(attrGroupVos);
		}, threadPoolConfig.threadPoolTaskExecutor());
		//4.获取spu介绍
		CompletableFuture<Void> descFuture = future.thenAcceptAsync((res) -> {
			MallSpuInfoDesc spuInfoDesc = iMallSpuInfoDescService.getById(res.getSpuId());
			skuItemVo.setDesc(spuInfoDesc);
		}, threadPoolConfig.threadPoolTaskExecutor());

		//sku的图片信息    pms_sku_images
		CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
			List<MallSkuImages> imagesEntities = iMallSkuImagesService.getImagesBySkuId(skuId);
			skuItemVo.setImages(imagesEntities);
		}, threadPoolConfig.threadPoolTaskExecutor());
		CompletableFuture.allOf(saleAttrFuture,baseAttrFuture,descFuture,imageFuture).get();
		return skuItemVo;
	}
}
